package myapp.Chat;

import org.jivesoftware.smack.ConnectionConfiguration;
import org.jivesoftware.smack.PacketListener;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.filter.PacketTypeFilter;
import org.jivesoftware.smack.packet.IQ;
import org.jivesoftware.smack.packet.Packet;
import org.jivesoftware.smack.packet.Presence;

import staticClass.XmppConnection;

import android.util.Log;

public class IQPacketSender {
	private String serviceName = "gmail.com";
	private XmppClient xmppClient;
	private XMPPConnection connection;
	
	public IQPacketSender(XmppClient client){
		xmppClient = client;
		Log.i("IQPacketSender", "In constructor.");
		this.CreateConnection("nguyenvanletay1@gmail.com", "toilatay");
	}
	
	private void CreateConnection(String username, String password){
		Log.i("IQPacketSender", "Trying to connect!");
		ConnectionConfiguration connConfig = new ConnectionConfiguration(serviceName);
		XMPPConnection connection = new XMPPConnection(connConfig);
		Log.i("IQPacketSender", "Trying to connect!2");
		try {
			connection.connect();
			Log.i("IQPacketSender", "[IQPacketSender] Connected to " + connection.getHost());
		} catch (XMPPException e) {
			// TODO: handle exception
			Log.e("IQPacketSender", "[IQPacketSender] Failed to connect to " + connection.getHost());
			//xmppClient.setConnection(null);
			XmppConnection.SetConnection(null);
		}
		
		try {
			connection.login(username, password);
			Log.i("IQPacketSender", "Logged in as " + connection.getUser());
			
			// Set the status to available
			Presence presence = new Presence(Presence.Type.available);
			connection.sendPacket(presence);
			//xmppClient.setConnection(connection);
			AddPacketListener(connection);
			this.connection = connection;
			
		} catch (XMPPException e) {
			// TODO: handle exception
			Log.e("IQPacketSender", "[SettingsDialog] Failed to log in as " + username);
//			xmppClient.setConnection(null);
			XmppConnection.SetConnection(null);
		}
		
	}
	
	private void AddPacketListener(XMPPConnection connection)	{
		connection.addPacketListener(new PacketListener() {
			
			public void processPacket(Packet packet) {
				// TODO Auto-generated method stub
				Log.i("IQPacketSender", "[ProcessPacket] " + packet.toXML());
			}
		}, new PacketTypeFilter(IQ.class));
	}
		
	public void SendTest()
	{
		IQ iq = new IQ() {

			@Override
			public String getChildElementXML() {
				// TODO Auto-generated method stub
				return "<query xmlns='http://jabber.org/protocol/disco#info'/>";
			}
		};

		iq.setType(IQ.Type.GET);
		iq.setTo("gmail.com");
		connection.sendPacket(iq);
		Log.i("IQPacketSender", "Packet sended: " + iq.toString());
	}
	
}
